package com.rraj.common;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * Created by hqm on 2017/6/26.
 * 统一处理创建时间修改时间
 */
@Component
@Aspect
public class DalAop {

    private static final String CREATETIME   = "createTime";
    private static final String UPDATETIME = "updateTime";


    @Before("execution(* com.rraj.mapper..*.insert*(..))")
    public void beforeInsert(JoinPoint jp) {
        Object[] args = jp.getArgs();

        if (args != null && args.length > 0) {
            Object argument = args[0];
            BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
            // 设置创建时间和修改时间
            if (beanWrapper.isWritableProperty(CREATETIME)) {
                beanWrapper.setPropertyValue(CREATETIME, new Date());
            }
            if (beanWrapper.isWritableProperty(UPDATETIME)) {
                beanWrapper.setPropertyValue(UPDATETIME, new Date());
            }



        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Before("execution(* com.rraj.mapper..*.update*(..)) || execution(* com.rraj.mapper..*.remove*(..)) || execution(* com.rraj.mapper..*.delete*(..))")
    public void beforeUpdate(JoinPoint jp) {

        Object[] args = jp.getArgs();
        // myBatis只能传递一个参数
        if (args != null && args.length > 0) {
            Object argument = args[0];

            // 如果argument是map类型
            if (argument instanceof Map) {
                Map map = (Map) argument;
                map.put(UPDATETIME, new Date());

            } else {
                BeanWrapper beanWrapper = new BeanWrapperImpl(argument);
                if (beanWrapper.isWritableProperty(UPDATETIME)) {
                    beanWrapper.setPropertyValue(UPDATETIME, new Date());
                }
            }
        }
    }
}
